package br.com.foxline.atlasmobile.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.Uri;
import br.com.foxline.atlasmobile.entities.Annex;

import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.QueryBuilder;

public class AnnexDao extends GenericDao<Annex> {

	private Context context;

	public AnnexDao(Context context) {
		super(context, new Annex());
		this.context = context;
	}

	/**
	 * Retorna array de uri das imagens do imovel passado por paramentro
	 * 
	 * @return
	 */
	public Uri[] getUris2(Long imovel) {
		List<Uri> resul = new ArrayList<Uri>();
		Uri[] r = {};
		GenericRawResults<String[]> rawResult;
		try {
			
			QueryBuilder<Annex, Long> qb = getDao().queryBuilder();
			qb.selectColumns("uri").where().eq("imovel", imovel);
			rawResult = getDao().queryRaw(qb.prepareStatementString());

			for (String[] strings : rawResult) {
				System.err.println(strings[0]);
				resul.add(Uri.parse(strings[0]));
			}
			r = new Uri[resul.size()];
			int cont = 0;
			for (Uri strings : resul) {
				r[cont] = strings;
				cont++;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
		return r;
	}

	public Uri[] getUris(Long imovel) {
		Uri[] resul = {};
		List<Annex> results = new ArrayList<Annex>();
		try {
			results = (List<Annex>) getDao().queryBuilder().where()
					.eq("imovel", imovel).query();

			resul = new Uri[results.size()];
			int i = 0;
			for (Annex annex : results) {
				resul[i] = Uri.parse(annex.getUri());
				i++;
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resul;
	}

	/**
	 * Retorna todos os imóveis que possuem anexo que não foram enviados.
	 * 
	 * @return
	 */
	public List<Long> exportOnlyAnnexNotSending() {

		List<Long> resul = new ArrayList<Long>();
		GenericRawResults<String[]> rawResult;
		try {

			rawResult = getDao().queryBuilder().selectColumns("imovel").where()
					.isNull("cod").queryRaw();

			for (String[] strings : rawResult) {
				if (strings[0] != null
						&& !resul.contains(Long.parseLong(strings[0]))) {
					resul.add(Long.parseLong(strings[0]));
				}
			}
			System.err.println(resul);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return resul;
	}

}
